package com.khalil.kkadmin.ai.rag.knowledgeset.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.khalil.kkadmin.ai.rag.knowledgeset.dto.RagKnowledgeSetCreateDto;
import com.khalil.kkadmin.ai.rag.knowledgeset.dto.RagKnowledgeSetUpdateDto;
import com.khalil.kkadmin.ai.rag.knowledgeset.entity.RagKnowledgeSet;
import com.khalil.kkadmin.ai.rag.knowledgeset.repository.RagKnowledgeSetRepository;
import com.khalil.kkadmin.ai.rag.knowledgeset.service.RagKnowledgeSetService;
import com.khalil.kkadmin.infrastructure.BaseService;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class RagKnowledgeSetServiceImpl extends BaseService<RagKnowledgeSetRepository, RagKnowledgeSet, Long> implements RagKnowledgeSetService {
    public RagKnowledgeSetServiceImpl(RagKnowledgeSetRepository repository) {
        super(repository);
    }

    @Override
    protected RagKnowledgeSet str2CreateEntity(String json) {
        RagKnowledgeSetCreateDto createDto = JSONObject.parseObject(json, RagKnowledgeSetCreateDto.class);
        RagKnowledgeSet ragKnowledgeSet = new RagKnowledgeSet();
        ragKnowledgeSet.setName(createDto.getName());
        ragKnowledgeSet.setDescription(createDto.getDescription());
        return ragKnowledgeSet;
    }

    @Override
    protected RagKnowledgeSet str2UpdateEntity(String json) {
        RagKnowledgeSetUpdateDto updateDto = JSONObject.parseObject(json, RagKnowledgeSetUpdateDto.class);
        Optional<RagKnowledgeSet> knowledgeSetOptional = repository.findById(updateDto.getId());
        if (knowledgeSetOptional.isPresent()) {
            RagKnowledgeSet ragKnowledgeSet = knowledgeSetOptional.get();
            ragKnowledgeSet.setName(updateDto.getName());
            ragKnowledgeSet.setDescription(updateDto.getDescription());
            return ragKnowledgeSet;
        }
        return null;
    }

    @Override
    public List<RagKnowledgeSet> list(String params) {
        return repository.findAll(Sort.by(Sort.Direction.ASC, "createdAt"));
    }
}
